<?
Prado::using('Application.pages.utils.CommonUtils');

class BooksUser extends TPage
{
	// Navigated ID
	public $id = -1;
	public $book = null;
	public $images = array();
	public $serverPathDownload = "user_images/";
	
	public $count = 0;
	public function onInit($param)
    {	
//        parent::onInit($param);
		if(!$this->IsPostBack)  // if the page is requested the first time
        {
			
		}
		
		
		$this->id = $this->Request['id'];
		echo "<input type=\"hidden\" id=\"uid\"  value=\"". $this->id."\" />";
		$this->setTitle($this->getCurrentRecord()->username ."'s Books");
		
		// load book count, book loader link
		$this->initBookData();
		
		// RETRICTED!: if navigator != owner .. someone watching our books, we're watching other books
		if(!$this->isNavigatedUserSameAsOwner())
		{
			$this->removeOwnerCmp();
		}
		else // navigator == owner 
		{
			
			$this->verifyResult();			
			$this->initImageData();
		}
		
	}
	
	public function initImageData()
	{
		

	
		// select the path of image of the user
		$sql = "SELECT ImagePath FROM tblimages_cnt where user_id = $this->id";
		$rec = TActiveRecord::finder('ImageCntRecord')->findAllBySql($sql);
		// write it into one js script
		echo "<script type=\"text/javascript\">";
		echo "var imagesUserArray = new Array();";
		for($i = 0;$i < sizeof($rec);$i++)
		{
			$path = $this->serverPathDownload . $this->id . "/cnt/" . $rec[$i]->ImagePath;
			//array_push($this->images,$path);
			echo "imagesUserArray.push(\"$path\");";

		}
		echo "</script>";
	}
	
	public function verifyResult()
	{
		if(isset($this->Request['resultcreatebook']))
		{
			$book_id = $this->Request['resultcreatebook'];
			//$this->bookResult->Text = "<div class=\"note\">";
			if($book_id == 200)
			{
				CommonUtils::setNotification($this->bookResult,"Your book has been created successfully");
			}
			else // 400
			{
				if($book_id == 400)
					CommonUtils::setError($this->bookResult,"Error when created book... ");
			}
			//$this->bookResult->Text .= "</div>";
		}
	}
	
	
	public function isNavigatedUserSameAsOwner()
	{
		return $this->id == $this->user->ID;
	}
	
	public function removeOwnerCmp()
	{
		$this->userPanel->Visible = false;
		
	}
	public function createbookClicked()
	{
			$url = $this->Service->constructUrl('users.Createbook',array('id' => $this->user->ID));

            $this->Response->redirect($url);
	
	}
	
	
	// public function loadBookData()
	// {
		
		// if(isset($this->Request['bid']))
		// {
			// $book_id = $this->Request['bid'];
			// $this->book = BookDataRecord::finder()->find('book_id = ?',$book_id);
			// $str = "Loaded book: ". $this->book->book_id;
			// for($i = 1;$i <= 20;$i++)
			// {
// //				$str = $str."<br/>p".$i." :".$this->book->{p.$i};	
				// $str = $str."<br/>p".$i." :".
				// "<textarea ID=\"p".$i . "\" row=2 >" . $this->loadPage($i)."</textarea>";
			// }

// //			$str = $str . "<br/>p1 :".$this->book->p1;
// // ...
// //			$str = $str . "<br/>p20 :".$this->book->p20;	
			// $this->bookDetails->Text = $str;
			// // show the button
			// $this->btnSaveBook->Visible = true;
		// }
	// }
	
	public function initBookData()
	{
		
		$this->Repeater_bookItem->VirtualItemCount = BookIDRecord::finder()->count('user_id = ?',$this->id);
		$this->bookCount->Text = $this->Repeater_bookItem->VirtualItemCount;
//		load book count + div style
		if($this->Repeater_bookItem->VirtualItemCount == 0) 
		{
			$str .= "Currently,  No books exists yet..";
			if($this->isNavigatedUserSameAsOwner()) $str .= "  click <b>Create</b> to get a new one!";
		}
		
		$this->populateBookDetails();
		
		$this->bookIDData->Text = $str;


	}
	
	public function populateBookDetails()
	{
		$offset = $this->Repeater_bookItem->CurrentPageIndex * $this->Repeater_bookItem->PageSize;
        $limit = $this->Repeater_bookItem->PageSize;
        
        if($offset + $limit > $this->Repeater_bookItem->VirtualItemCount)
            $limit=$this->Repeater_bookItem->VirtualItemCount - $offset;
            
        $this->Repeater_bookItem->DataSource=$this->getLists_BookDetails($offset,$limit);
        $this->Repeater_bookItem->dataBind();
	}
	
	public function getLists_BookDetails($offset,$limit)
	{
		        // Construts a query criteria
        $criteria = new TActiveRecordCriteria;		
		$criteria->Condition = 'user_id = :id';
		$criteria->Parameters[':id'] = $this->id;
        
        $criteria->Limit=$limit;
        $criteria->Offset=$offset;

        // query for the posts with the above criteria and with author information
        return BookIDRecord::finder()->findAll($criteria);
	}
	
	public function bookItem_pageChanged($sender,$param)
    {
        // change the current page index to the new one
        $this->Repeater_bookItem->CurrentPageIndex = $param->NewPageIndex;
        // re-populate data into the repeater
        $this->populateImagesCnt();
    }
    
	public function getBookName($book_id)
	{
		$book = BookDataRecord::finder()->find('book_id = ?',$book_id);
		return $book->book_name;
	}
	
//	public function insertRecord($finder)
//	{
//		$f_id = $finder->user_id;
//		//$owner = UserRecord::finder()->findByEmail($this->user->Email);
//		
//		$u_id = $this->User->ID;
//		$newRec = new FriendReqRecord();
//		$newRec->user_id = $u_id;
//		$newRec->friend_id = $f_id;
//		$newRec->datetime_request = date("Y/m/d H:i:s");
//		$newRec->save();
//	}

	public function saveBookClicked($sender,$param)
    {
      		for($i = 1;$i <= 20;$i++)
			{
				$this->savePage($i,"<sub7>ss</sub7><good />");

			}
    }

	/**
	 * For art
	 * $index = [1,20]
	 */
	public function loadPage($index)
	{
		$xmlret = "";
		$xmlret = $this->book->{p.$index};
		return $xmlret;	
	}
	
	/**
	 * For art
	 * $index = [1,20]
	 */
	public function savePage($index, $xml)
	{
		$this->book->{p.$index} = $xml;
		$this->book->save();
	}
	
	public function getOwnerRecord()
	{
	
	//	$userRecord = UserRecord::finder()->findByEmail($this->user->Email); $this->id
		$userRecord = UserRecord::finder()->findByUser_Id($this->user->ID);
		return $userRecord;
	}
	
	public function getCurrentRecord()
	{
	
	//	$userRecord = UserRecord::finder()->findByEmail($this->user->Email); $this->id
		$userRecord = UserRecord::finder()->findByUser_Id($this->id);
		return $userRecord;
	}
   
}

?>